package appIdeasScrumer.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import appIdeasScrumer.excepcion.DAOExcepcion;
import appIdeasScrumer.modelo.Cobro;
import appIdeasScrumer.negocio.GestionCentroFormacion;
import appIdeasScrumer.negocio.GestionCobro;
import appIdeasScrumer.util.ConexionBD;

public class CobroDAO extends BaseDAO {

	public Collection<Cobro> listar() throws DAOExcepcion {
		Collection<Cobro> cobro = new ArrayList<Cobro>();
		Connection cnx = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			cnx = ConexionBD.obtenerConexion();
			String query = "select cod_centro, cnt_profesor, cnt_coordinador, cnt_usuario, mon_subtotal, mon_igv, mon_total " +
				"from tc_cobro order by cod_centro";
			stmt = cnx.prepareStatement(query);
			rs = stmt.executeQuery();
			while (rs.next()) {
				GestionCentroFormacion gcf = new GestionCentroFormacion();
				GestionCobro gc = new GestionCobro();
				Cobro c = new Cobro();
				Double subtotal = 0.00;
				int cod = rs.getInt("cod_centro");
				
				c.setCentrof(gcf.obtener(cod));
				c.setCntProf(rs.getInt("cnt_profesor"));
				c.setCntCoord(rs.getInt("cnt_coordinador"));
				c.setCntAlumno(rs.getInt("cnt_usuario"));
				
				subtotal = gc.calcularCobro(rs.getInt("cnt_profesor"),rs.getInt("cnt_coordinador"),rs.getInt("cnt_usuario"));
				Double igv = subtotal * 0.18;
				Double total = subtotal + (subtotal * 0.18);
				
				c.setSubtotal(subtotal);
				c.setIGV(igv); //VALOR IGV 18%
				c.setTotal(total);
				cobro.add(c);
				
				gc.update(cod, subtotal, igv, total);
				
			}
	
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(cnx);
		}
		return cobro;

	}
	
	public void update(int cod, Double subtotal, Double igv, Double total) throws DAOExcepcion {
		String query = "update tc_cobro set mon_subtotal=?,mon_igv=?, mon_total=? where cod_centro=?";
		Connection cnx = null;
		PreparedStatement stmt = null;
		try {
			cnx = ConexionBD.obtenerConexion();
			stmt = cnx.prepareStatement(query);
			stmt.setDouble(1, subtotal);
			stmt.setDouble(2, igv);
			stmt.setDouble(3, total);
			stmt.setInt(4, cod);
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo actualizar");
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarStatement(stmt);
			this.cerrarConexion(cnx);
		}
	}


}
